package com.atguigu.gmall.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.mapper.*;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.service.ManagerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ManagerServiceImpl extends ServiceImpl<BaseAttrValueMapper, BaseAttrValue> implements ManagerService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;


    // 注意：以下Mapper已通过ServiceImpl的saveBatch方法实现批量插入，无需直接使用
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuPosterMapper spuPosterMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> baseCategory1s = baseCategory1Mapper.selectList(null);
        return baseCategory1s;
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where category1_id = category1Id and  is_delete = 0;
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    //  ctrl+i ： 提示未实现的方法  shift+f2：快速定位错误行
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  select * from base_category3 where category2_id = category2Id and  is_delete = 0;
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {

        //  调用mapper
        return baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)   //  只要有异常信息就回滚数据.
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        /*
        base_attr_info
        base_attr_value
         */

        //  base_attr_info判断是修改{id != null }，还是保存！{id = null}
        if (baseAttrInfo.getId() != null) {
            //  修改
            this.baseAttrInfoMapper.updateById(baseAttrInfo);


            List<BaseAttrValue> oldlist = baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId()));
            List<BaseAttrValue> newList = baseAttrInfo.getAttrValueList();

            //删掉没有传过来的
            if (!CollectionUtils.isEmpty(oldlist)) {
                oldlist.forEach(baseAttrValue -> {
                    boolean b = newList.stream().anyMatch(baseAttrValue1 -> baseAttrValue1.getId().equals(baseAttrValue.getId()));
                    if (!b) {
//                        baseAttrValueMapper.deleteById(baseAttrValue.getId());
//                        baseAttrValueMapper.delete(new QueryWrapper<BaseAttrValue>().eq("id", baseAttrValue.getId()));
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", baseAttrValue.getId());
                        System.out.println("map==================================== = " + map);
                        baseAttrValueMapper.deleteByMap(map);
                    }
                });

            }
            //保存多出来的
            List<BaseAttrValue> addedList = newList.stream()
                    .filter(newItem -> oldlist.stream()
                            .noneMatch(oldItem -> oldItem.getId().equals(newItem.getId())))
                    .collect(Collectors.toList());
            for (BaseAttrValue baseAttrValue : addedList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
            }
            this.saveBatch(addedList);
        } else {
            baseAttrInfoMapper.insert(baseAttrInfo);
            //  获取平台属性值集合数据
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
            if (!CollectionUtils.isEmpty(attrValueList)) {
                attrValueList.forEach(baseAttrValue -> {
                    //  细节：attr_id = base_attr_info.id
                    //  @TableId(type = IdType.AUTO) 获取到主键自增！
                    baseAttrValue.setAttrId(baseAttrInfo.getId());
//                baseAttrValueMapper.insert(baseAttrValue);
                });
            }
            this.saveBatch(attrValueList);
        }


    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectAttrInfo(attrId);
        return baseAttrInfo;
    }

    @Override
    public IPage<SpuInfo> getSpuInfoPage(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id", spuInfo.getCategory3Id());
        queryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(spuInfoPage, queryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        List<BaseSaleAttr> baseSaleAttrs = baseSaleAttrMapper.selectList(null);
        return baseSaleAttrs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();// 商品的图片集合
        if (spuImageList != null) {
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();// 销售属性集合
        if (spuSaleAttrList != null) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                if (spuSaleAttr.getSpuSaleAttrValueList() != null) {
                    spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setBaseSaleAttrId(spuSaleAttr.getBaseSaleAttrId());

                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }

            }
        }
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();// 商品的海报图片集合
        if (spuPosterList != null) {
            for (SpuPoster spuPoster : spuPosterList) {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            }
        }

        return Result.ok();
    }

    @Override
    public Result getSpuInfo(Long spuId) {
        SpuInfo spuInfo = spuInfoMapper.selectById(spuId);
        List<SpuImage> images = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        spuInfo.setSpuImageList(images);
        List<SpuPoster> posters = spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
        spuInfo.setSpuPosterList(posters);

        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectList(new QueryWrapper<SpuSaleAttr>().eq("spu_id", spuId));

        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttrValueMapper.selectList(new QueryWrapper<SpuSaleAttrValue>()
                    .eq("spu_id", spuId)
                    .eq("base_sale_attr_id", spuSaleAttr.getBaseSaleAttrId()));
            spuSaleAttr.setSpuSaleAttrValueList(spuSaleAttrValueList);
        }
        spuInfo.setSpuSaleAttrList(spuSaleAttrList);

        return Result.ok(spuInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.updateById(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();// 商品的图片集合
        spuImageMapper.delete(new QueryWrapper<SpuImage>().eq("spu_id", spuInfo.getId()));
        spuSaleAttrMapper.delete(new QueryWrapper<SpuSaleAttr>().eq("spu_id", spuInfo.getId()));
        spuPosterMapper.delete(new QueryWrapper<SpuPoster>().eq("spu_id", spuInfo.getId()));
        spuSaleAttrValueMapper.delete(new QueryWrapper<SpuSaleAttrValue>().eq("spu_id", spuInfo.getId()));
        if (spuImageList != null) {
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();// 销售属性集合
        if (spuSaleAttrList != null) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                if (spuSaleAttr.getSpuSaleAttrValueList() != null) {
                    spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setBaseSaleAttrId(spuSaleAttr.getBaseSaleAttrId());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            }
        }
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();// 商品的海报图片集合
        if (spuPosterList != null) {
            for (SpuPoster spuPoster : spuPosterList) {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            }
        }
        return Result.ok();
    }

    @Override
    public Result getSpuSaleAttrList(Long spuId) {
//        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectList(new QueryWrapper<SpuSaleAttr>().eq("spu_id", spuId));
//        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
//            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttrValueMapper.selectList(new QueryWrapper<SpuSaleAttrValue>()
//                    .eq("spu_id", spuId)
//                    .eq("base_sale_attr_id", spuSaleAttr.getBaseSaleAttrId()));
//            spuSaleAttr.setSpuSaleAttrValueList(spuSaleAttrValueList);
//        }
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.getSpuSaleAttrList(spuId);
        return Result.ok(spuSaleAttrList);

    }

    @Override
    public Result getSpuImageList(Long spuId) {
        List<SpuImage> spuImageList = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        return Result.ok(spuImageList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        skuInfoMapper.insert(skuInfo);
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();//sku图片集合
        for (SkuImage skuImage : skuImageList) {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        }


        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();//sku平台属性集合
        for (SkuAttrValue skuAttrValue : skuAttrValueList) {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        }

        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();//sku销售属性集合
        for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        }

    }

    @Override
    public Result list(Page<SkuInfo> spuInfoPage, Long category3Id) {
        IPage<SkuInfo> skuInfo = skuInfoMapper.selectPage(spuInfoPage, new QueryWrapper<SkuInfo>().eq("category3_id", category3Id));


        return Result.ok(skuInfo);

    }

    @Override
    public Result getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
        skuInfo.setSkuImageList(skuImageList);
        List<SkuAttrValue> skuAttrValueList = skuAttrValueMapper.selectList(new QueryWrapper<SkuAttrValue>().eq("sku_id", skuId));
        for (SkuAttrValue skuAttrValue : skuAttrValueList) {
            BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(skuAttrValue.getAttrId());
            skuAttrValue.setAttrName(baseAttrInfo.getAttrName());
            BaseAttrValue baseAttrValue = baseAttrValueMapper.selectById(skuAttrValue.getValueId());
            skuAttrValue.setValueName(baseAttrValue.getValueName());
        }
        skuInfo.setSkuAttrValueList(skuAttrValueList);

        List<SkuSaleAttrValue> skuSaleAttrValueList = skuSaleAttrValueMapper.selectList(new QueryWrapper<SkuSaleAttrValue>().eq("sku_id", skuId));
        for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
            SpuSaleAttrValue spuSaleAttrValue = spuSaleAttrValueMapper.selectById(skuSaleAttrValue.getSaleAttrValueId());
            skuSaleAttrValue.setSpuId(spuSaleAttrValue.getSpuId());
            skuSaleAttrValue.setBaseSaleAttrId(spuSaleAttrValue.getBaseSaleAttrId());
            skuSaleAttrValue.setSaleAttrName(spuSaleAttrValue.getSaleAttrName());
            skuSaleAttrValue.setSaleAttrValueName(spuSaleAttrValue.getSaleAttrValueName());
            skuSaleAttrValue.setSaleAttrValueId(spuSaleAttrValue.getId());


        }
        skuInfo.setSkuSaleAttrValueList(skuSaleAttrValueList);

        return Result.ok(skuInfo);

    }

    @Override
    public Result onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
        return Result.ok("上架成功");
    }

    @Override
    public Result cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        return Result.ok("下架成功");
    }


}
